package com.kbt.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.util.Xml;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.*;
import com.alipay.sdk.app.PayTask;
import com.android.volley.Request;
import com.google.gson.Gson;
import com.kbt.adapter.GoodForPayAdapter;
import com.kbt.base.BaseApplication;
import com.kbt.commont.Constants;
import com.kbt.model.data.*;
import com.kbt.net.RequestManager;
import com.kbt.simcpux.MD5;
import com.kbt.simcpux.Util;
import com.kbt.util.data.StaticData;
import com.kbt.util.pay.PayResult;
import com.kbt.util.pay.PayUtil;
import com.kbt.util.tool.CommonStatus;
import com.kbt.util.tool.RestListViewSizeTool;
import com.kbt.util.utils.LoadingDialog;
import com.kbt.util.utils.NoScrollListView;
import com.kbt.util.utils.SharePreferenceUtils;
import com.kbt.util.utils.Utils;
import com.tencent.mm.sdk.modelpay.PayReq;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.xmlpull.v1.XmlPullParser;

import java.io.Serializable;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author zhgk
 * @package: com.kbt.activity
 * @TODO: 确认订单
 * @data: 2015/8/13 15:38
 * @version: V1.0
 */
public class GoodForPayActivity extends Activity implements RequestManager.ResponseInterface {
    private List<ShopCarBean> goodInfoList;
    private NoScrollListView goodInfoListView;
    private GoodForPayAdapter adapter;
    public static BigDecimal totalPrice = new BigDecimal(0);
    private RequestManager mRequestManager;
    private Map<String, Object> map = null;
    private LinearLayout noAddressL;
    private LinearLayout defaultAddressL;
    private AddressBeans addressBeans;
    private AddressBean addressBean=null;
    private TextView car_cp_totalFee;
    private ImageView weixin_image;
    private ImageView zhifubao_image;
    private RelativeLayout rl_weixin;
    private RelativeLayout rl_zhifubao;
    private String payWay;//支付方式(1.支付宝支付 2.微信支付)
    private ImageView dikou;
    private AlertDialog mDlg;
    private JiFenBeans jiFenBeans;
    private BaseBean baseBean;
    private TextView jifen;
    private TextView discountMoney;
    private Map<String, String> postMap;
    public static String orderNo;//订单号
    private TextView hyyh;//订单优惠
    private TextView kuaidi;//快递
    private TextView vip;//会员
    private TextView shifu;//实付金额
    private EditText edit_jifen;//用户所用积分
    private ShopCarListBean shopCarListBean;
    private List<ShopCarBean> shopCarBeans = new ArrayList<ShopCarBean>();
    private SharePreferenceUtils share;
    private String phone;
    private Intent intent;
    public static   String  biaoji="";
    private TextView orderZongJi;
    private TextView dialog_jifen;
    //微信支付
    PayReq req;
    final IWXAPI msgApi = WXAPIFactory.createWXAPI(this, null);
    Map<String,String> resultunifiedorder;
    StringBuffer sb;
    private String order_jf_sub_je;
    private LoadingDialog mProgress;
    //库存
    private List<KuCunBean> kuCunBeans = new ArrayList<KuCunBean>();
    private KuCunListBean kuCunListBean;
    private Map<String,String> kunCunMap = new HashMap<String,String>();

    public static EditText edit_jifen_payMoney;
    public static  TextView shiyong_money;

    public static String pre_id="";




    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case PayUtil.SDK_PAY_FLAG: {
                    PayResult payResult = new PayResult((String) msg.obj);
                    // 支付宝返回此次支付结果及加签，建议对支付宝签名信息拿签约时支付宝提供的公钥做验签
                    String resultInfo = payResult.getResult();
                    String resultStatus = payResult.getResultStatus();

                    // 判断resultStatus 为“9000”则代表支付成功，具体状态码代表含义可参考接口文档
                    if (TextUtils.equals(resultStatus, "9000")) {
                        httpPaySuccess();
//                        Toast.makeText(GoodForPayActivity.this, "支付成功",
//                                Toast.LENGTH_SHORT).show();
                    } else {
                        // 判断resultStatus 为非“9000”则代表可能支付失败
                        // “8000”代表支付结果因为支付渠道原因或者系统原因还在等待支付结果确认，最终交易是否成功以服务端异步通知为准（小概率状态）
                        if (TextUtils.equals(resultStatus, "8000")) {
                            Toast.makeText(GoodForPayActivity.this, "支付结果确认中",
                                    Toast.LENGTH_SHORT).show();

                        } else {
                            // 其他值就可以判断为支付失败，包括用户主动取消支付，或者系统返回的错误
//                            biaoji="noPayMoney";
                            order_jf_sub_je = discountMoney.getText().toString().split("￥")[1];
                            shiyong_money.setText("已使用");
                            edit_jifen_payMoney.setFocusable(false);
                            Toast.makeText(GoodForPayActivity.this, "您尚未支付成功，如继续购买，请点击去付款",
                                    Toast.LENGTH_SHORT).show();

                        }
                    }
                    break;
                }
                case PayUtil.SDK_CHECK_FLAG: {
                    Toast.makeText(GoodForPayActivity.this, "检查结果为：" + msg.obj,
                            Toast.LENGTH_SHORT).show();
                    break;
                }
                default:
                    break;
            }
        }

    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        this.requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
        setContentView(R.layout.good_for_pay);
        this.getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.title_return_btn);

        mRequestManager = new RequestManager();
        mRequestManager.setResponseListener(this);
        map = new HashMap<String, Object>();
        postMap = new HashMap<String, String>();
        intent =getIntent();
        biaoji =intent.getStringExtra("biaoji");

        //设置标题内容
        TextView textView = (TextView) findViewById(R.id.center_title);
        textView.setText(StaticData.GOODS_FOR_PAY);

        //设置返回按钮事件
        ImageView returnImg = (ImageView) findViewById(R.id.return_btn);
        Class target = StoreActivity.class;
        returnImg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                BaseApplication.getInstance().removeActivity(GoodForPayActivity.this);
                if ("shopcar".equals(biaoji)) {
                    Intent intent = new Intent(GoodForPayActivity.this, StoreActivity.class);
                    startActivity(intent);
                } else if ("buyNow".equals(biaoji)) {
                    Intent intent = new Intent(GoodForPayActivity.this, GoodInfoActivity.class);
                    intent.putExtra("shopId", goodInfoList.get(0).getGoods_id());
                    startActivity(intent);
                }
                finish();
            }
        });
        //微信支付
        req = new PayReq();
        sb=new StringBuffer();
        msgApi.registerApp(com.kbt.simcpux.Constants.APP_ID);
        //初始化
        init();
        //获取积分
        httpJiFen();


    }

    @Override
    protected void onStart() {
        super.onStart();

        BaseApplication.getInstance().addActivity(GoodForPayActivity.this);
        BaseApplication.getInstance().addActivitytwo(GoodForPayActivity.this);
        SimpleDateFormat simplepre = new SimpleDateFormat("yyyyMMddhhmmssSSSss");
        pre_id = simplepre.format(new Date());

        if(getIntent().getStringExtra("orderNo")!=null&&!"".equals(getIntent().getStringExtra("orderNo"))){
            orderNo =getIntent().getStringExtra("orderNo") ;
        }

    }

    private void setListener() {
        rl_weixin.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                payWay = "2";
                weixin_image
                        .setImageResource(R.drawable.checkbox2_selected);
                zhifubao_image
                        .setImageResource(R.drawable.checkbox2_unselect);
            }
        });
        rl_zhifubao.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                payWay = "1";
                weixin_image
                        .setImageResource(R.drawable.checkbox2_unselect);
                zhifubao_image
                        .setImageResource(R.drawable.checkbox2_selected);
            }
        });
        dikou.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                createDialog();
            }
        });
        edit_jifen_payMoney.addTextChangedListener(textWatcher);

    }

    //增加订单
    private void httpAddOrder() {
        int shopNumber =0;
        if(goodInfoList.size()>0){
            for(int i=0;i<goodInfoList.size();i++){
                shopNumber +=Integer.parseInt(goodInfoList.get(i).getGoods_count());
            }
        }
        if(Utils.isNetworkAvailable(GoodForPayActivity.this)) {
            Gson gson = new Gson();
            postMap.clear();
            postMap.put("methodType", "add");
            Map dataMap = new HashMap<String,String>();
            dataMap.put("order_no", orderNo);
            dataMap.put("goods_count", shopNumber);
            dataMap.put("order_total_je", orderZongJi.getText().toString());//订单总计
            dataMap.put("goods_je", new DecimalFormat("#.##").format(totalPrice));
            dataMap.put("kd_je", BaseApplication.getInstance().freight);
            dataMap.put("order_sub_je", hyyh.getText().toString());//订单优惠
            dataMap.put("order_jf_sub_je", discountMoney.getText().toString().split("￥")[1]);
            dataMap.put("kd_sub_je", kuaidi.getText().toString().split("￥")[1]);
            dataMap.put("member_sub_je", vip.getText().toString().split("￥")[1]);
            dataMap.put("yhq_sub_je", "");//优惠劵减免
            dataMap.put("order_real_je", shifu.getText().toString());
            dataMap.put("order_create_time", new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date()));
            dataMap.put("order_zs_jf", shifu.getText().toString());//1元1分
            dataMap.put("order_dk_jf", Double.parseDouble(discountMoney.getText().toString().split("￥")[1]) * 100);
            dataMap.put("order_status", null);
            dataMap.put("order_user_name", addressBean.getUser_name());
            dataMap.put("order_user_mobile", addressBean.getUser_mobile());
            dataMap.put("order_user_address", addressBean.getUser_address_sxq());
            dataMap.put("order_pay_type", payWay);
            dataMap.put("order_type", "2");
            dataMap.put("order_create_user", phone);
            dataMap.put("order_address_id", addressBean.getAddress_id());
            dataMap.put("goods_list", goodInfoList);
            postMap.put("data", gson.toJson(dataMap));
            mRequestManager.post(Constants.ServiceInterFace.addOrderURL, postMap, Constants.RequestTag.addOrderTag, BaseBean.class);
        }else{
            Toast.makeText(GoodForPayActivity.this,R.string.Wangluo,Toast.LENGTH_SHORT).show();
        }
    }
    //支付成功
    private  void httpPaySuccess(){
        if(Utils.isNetworkAvailable(GoodForPayActivity.this)) {
            Gson gson = new Gson();
            postMap.clear();
            postMap.put("methodType", "payOrder");
            Map dataMap = new HashMap<String,String>();
            dataMap.put("order_no", orderNo);
            dataMap.put("pay_je", new DecimalFormat("#.##").format(totalPrice));
            dataMap.put("pay_user", "");
            dataMap.put("pay_account", "");
            dataMap.put("pay_type", payWay);
            dataMap.put("pay_time", "");
            dataMap.put("ace_account", PayUtil.SELLER);
            dataMap.put("pay_no", pre_id);
            postMap.put("data", gson.toJson(dataMap));
            mRequestManager.post(Constants.ServiceInterFace.paySuccessURL, postMap, Constants.RequestTag.paySuccessTag, BaseBean.class);
        }else{
            Toast.makeText(GoodForPayActivity.this,R.string.Wangluo,Toast.LENGTH_SHORT).show();
        }
    }

    //获取积分
    private void httpJiFen() {
        showProgress();
        if(Utils.isNetworkAvailable(GoodForPayActivity.this)) {
            mRequestManager.requestGet(Request.Method.GET, Constants.ServiceInterFace.selectJiFenURL + phone, Constants.RequestTag.selectJiFenTag, map, JiFenBeans.class);
        }else{
            Toast.makeText(GoodForPayActivity.this,R.string.Wangluo,Toast.LENGTH_SHORT).show();
        }
    }
    //初始化
    private void init(){
        shiyong_money = (TextView) findViewById(R.id.shiyong_money);
        edit_jifen_payMoney = (EditText) findViewById(R.id.edit_jifen_payMoney);
        share = new SharePreferenceUtils(GoodForPayActivity.this);
        phone = share.getString("user_mobile", "");
        orderZongJi = (TextView) findViewById(R.id.orderZongJi);
        weixin_image = (ImageView) findViewById(R.id.weixin_image);
        zhifubao_image = (ImageView) findViewById(R.id.zhifubao_image);
        rl_weixin = (RelativeLayout) findViewById(R.id.rl_weixin);
        rl_zhifubao = (RelativeLayout) findViewById(R.id.rl_zhifubao);
        dikou = (ImageView) findViewById(R.id.dikou);
        if(getIntent().getStringExtra("orderNo")!=null&&!"".equals(getIntent().getStringExtra("orderNo"))) {
            dikou.setVisibility(View.INVISIBLE);
        }
        jifen = (TextView) findViewById(R.id.jifen);

        discountMoney = (TextView) findViewById(R.id.discountMoney);
        order_jf_sub_je = getIntent().getStringExtra("order_jf_sub_je");

        hyyh = (TextView) findViewById(R.id.hyyh);
        kuaidi = (TextView) findViewById(R.id.kuaidi);
        vip = (TextView) findViewById(R.id.vip);
        shifu = (TextView) findViewById(R.id.shifu);
        //默认选择支付宝
        payWay = "1";
        weixin_image
                .setImageResource(R.drawable.checkbox2_unselect);
        zhifubao_image
                .setImageResource(R.drawable.checkbox2_selected);
    }

    //提交订单弹出的确认dialog
    private void createDialog() {
        if (mDlg == null) {
            mDlg = new AlertDialog.Builder(this).create();
        }

        mDlg.show();
        // 点击对话框外部取消对话框显示
        mDlg.setCanceledOnTouchOutside(true);
        Window window = mDlg.getWindow();
        //解决alterdialog点击edittext无法弹出键盘的问题
        mDlg.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
        window.setContentView(R.layout.dialog_unupload);

        dialog_jifen = (TextView) window.findViewById(R.id.dialog_jifen);
        if(jiFenBeans.getData()!=null){
            dialog_jifen.setText(jiFenBeans.getData().getAvailable_point()+"");
        }
        final TextView money = (TextView) window.findViewById(R.id.money);
        edit_jifen = (EditText) window.findViewById(R.id.edit_jifen);
        Button btn_duihuan = (Button) window.findViewById(R.id.btn_duihuan);

        Button ok = (Button) window.findViewById(R.id.dlg_btn_ok);
        ImageView no = (ImageView) window.findViewById(R.id.dlg_btn_no);
        btn_duihuan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int jifen_window = 0;
                if (!"".equals(edit_jifen_payMoney.getText().toString())) {
                    jifen_window = Integer.parseInt(edit_jifen_payMoney.getText().toString());
                    if (jifen_window <= Integer.parseInt(dialog_jifen.getText().toString())) {
                        double duihuan_money = jifen_window / 100.0;
                        double jifenmoney = Double.parseDouble(orderZongJi.getText().toString());//订单总计
                        if(duihuan_money>jifenmoney){
                            Toast.makeText(GoodForPayActivity.this, "您最多抵扣"+jifenmoney*100+"积分", Toast.LENGTH_SHORT).show();
                            return;
                        }
                        money.setText(duihuan_money + "");
                    } else {
                        Toast.makeText(GoodForPayActivity.this, "积分不足！", Toast.LENGTH_SHORT).show();
                    }
                } else {
                    money.setText("0");
                }
            }
        });

        ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                discountMoney.setText("￥" + money.getText().toString());
                if (money.getText().toString().equals("0")) {
                    double zongjiMoney = Double.parseDouble(orderZongJi.getText().toString());
                    shifu.setText(new DecimalFormat("#.##").format(zongjiMoney) + "");
                    car_cp_totalFee.setText(new DecimalFormat("#.##").format(zongjiMoney) + "");
                }
                double shifuMoney = Double.parseDouble(orderZongJi.getText().toString()) - Double.parseDouble(money.getText().toString());
                shifu.setText(new DecimalFormat("#.##").format(shifuMoney) + "");
                hyyh.setText(money.getText().toString());
                car_cp_totalFee.setText(new DecimalFormat("#.##").format(shifuMoney) + "");
                mDlg.dismiss();
            }
        });
        no.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mDlg.dismiss();
            }
        });

    }

    /**
     * 初始化视图数据
     */
    private void initListView() {
        goodInfoListView = (NoScrollListView) findViewById(R.id.pay_good_listView);
        adapter = new GoodForPayAdapter(this, goodInfoList);
        goodInfoListView.setAdapter(adapter);
    }

    /***
     * 初始化数据
     */
    private void initListViewData() {
        goodInfoList = new ArrayList<ShopCarBean>();
        car_cp_totalFee = (TextView) findViewById(R.id.car_cp_totalFee);

        if(biaoji!=null) {
            if(biaoji.equals("buyNow")&&order_jf_sub_je==null){
                orderNo="";
            }
            if(biaoji.equals("noPayMoney")){
                edit_jifen_payMoney.setFocusable(false);
                shiyong_money.setText("已使用");
            }
            if (biaoji.equals("buyNow") || biaoji.equals("noPayMoney")) {
                goodInfoList = (List<ShopCarBean>) getIntent().getSerializableExtra("list");
                BaseApplication.getInstance().shopCarBeans = (List<ShopCarBean>) getIntent().getSerializableExtra("list");
                ShopCarBean item;
                totalPrice = new BigDecimal(0);
                for (int i = 0; i < goodInfoList.size(); i++) {
                    item = goodInfoList.get(i);
//                    totalPrice += Float.parseFloat(item.getGoods_count()) * item.getGoods_new_price();
                    totalPrice=totalPrice.add(new BigDecimal(String.valueOf(item.getGoods_count())).multiply(new BigDecimal(String.valueOf(item.getGoods_new_price())))) ;
                }

                orderZongJi.setText(totalPrice.setScale(2, BigDecimal.ROUND_HALF_UP).toString());//订单总计
                if (biaoji.equals("buyNow")){
                    if ((totalPrice.multiply(new BigDecimal(100)).intValue()) > Integer.parseInt(jiFenBeans.getData().getAvailable_point())) {
                        edit_jifen_payMoney.setText(jiFenBeans.getData().getAvailable_point() + "");
                    } else {
                        edit_jifen_payMoney.setText(totalPrice.multiply(new BigDecimal(100)).setScale(0, BigDecimal.ROUND_HALF_UP).toString());
                    }
                }
                if (order_jf_sub_je != null && !"".equals(order_jf_sub_je)) {
                    edit_jifen_payMoney.setFocusable(false);
                    shiyong_money.setText("已使用");
                    discountMoney.setText("￥"+order_jf_sub_je);
                    edit_jifen_payMoney.setText(new BigDecimal(discountMoney.getText().toString().split("￥")[1]).multiply(new BigDecimal(100)).setScale(0, BigDecimal.ROUND_HALF_UP).toString());
                }else{
                    discountMoney.setText("￥"+new BigDecimal(edit_jifen_payMoney.getText().toString()).divide(new BigDecimal(100)).setScale(2, BigDecimal.ROUND_HALF_UP).toString());
                }
                hyyh.setText(new BigDecimal(edit_jifen_payMoney.getText().toString()).divide(new BigDecimal(100)).setScale(2, BigDecimal.ROUND_HALF_UP).toString());
                car_cp_totalFee.setText(totalPrice.subtract(new BigDecimal(hyyh.getText().toString())).setScale(2, BigDecimal.ROUND_HALF_UP).toString());
                shifu.setText(totalPrice.subtract(new BigDecimal(hyyh.getText().toString())).setScale(2, BigDecimal.ROUND_HALF_UP).toString());//实付
            } else{
                showProgress();
                if(Utils.isNetworkAvailable(GoodForPayActivity.this)) {
                    mRequestManager.requestGet(Request.Method.GET, Constants.ServiceInterFace.selectShopCarURL + phone + "&methodType=queryGoodsList", Constants.RequestTag.selectShopCarTag, map, ShopCarListBean.class);
                }else{
                    Toast.makeText(GoodForPayActivity.this,R.string.Wangluo,Toast.LENGTH_SHORT).show();
                }
            }
        }else{
            showProgress();
            if(Utils.isNetworkAvailable(GoodForPayActivity.this)) {
                mRequestManager.requestGet(Request.Method.GET, Constants.ServiceInterFace.selectShopCarURL + phone + "&methodType=queryGoodsList", Constants.RequestTag.selectShopCarTag, map, ShopCarListBean.class);
            }else{
                Toast.makeText(GoodForPayActivity.this, R.string.Wangluo,Toast.LENGTH_SHORT).show();
            }
        }
    }

    private void initBottomBtn() {
        Button payBtn = (Button) findViewById(R.id.car_cp_jsbtn);
        payBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (addressBean == null) {
                    Intent intent = new Intent(GoodForPayActivity.this, AddressAddActivity.class);
                    intent.putExtra("tag", "1");
                    intent.putExtra("biaoji", biaoji);
                    if(BaseApplication.getInstance().isWeixin) {
                        intent.putExtra("list", (Serializable) BaseApplication.getInstance().shopCarBeans);
                        order_jf_sub_je = discountMoney.getText().toString().split("￥")[1];
                    }else{
                        intent.putExtra("list", (Serializable) goodInfoList);
                    }
                    if (order_jf_sub_je != null && !"".equals(order_jf_sub_je)) {
                        intent.putExtra("order_jf_sub_je", order_jf_sub_je);
                    }
                    startActivity(intent);
                    BaseApplication.getInstance().removeActivity(GoodForPayActivity.this);
                    finish();
                    return;
                }

                httpKunCun();

            }
        });
    }
    //查询库存
    private void httpKunCun(){
        String goods_id = "";
        for(int i=0;i<goodInfoList.size();i++){
            goods_id += "\'" + goodInfoList.get(i).getGoods_id() + "\'" + ",";
        }
        showProgress();
        if(Utils.isNetworkAvailable(GoodForPayActivity.this)) {
            mRequestManager.requestGet(Request.Method.GET, Constants.ServiceInterFace.selectKunCunURL + goods_id.substring(0, goods_id.length() - 1), Constants.RequestTag.selectKunCunTag, map, KuCunListBean.class);
        }else{
            stopProgress();
            Toast.makeText(GoodForPayActivity.this,R.string.Wangluo,Toast.LENGTH_SHORT).show();
        }
    }
    //修改支付方式
    private void httpUpdatePayType(){
        showProgress();
        if(Utils.isNetworkAvailable(GoodForPayActivity.this)) {
        Gson gson = new Gson();
        postMap.clear();
        postMap.put("methodType", "updatePayType");
        Map dataMap = new HashMap<String,String>();
        dataMap.put("pay_type",payWay);
        dataMap.put("order_no",orderNo);
        postMap.put("data", gson.toJson(dataMap));
        mRequestManager.post(Constants.ServiceInterFace.updatePayTypeURL, postMap, Constants.RequestTag.updatePayTypeTag, BaseBean.class);
        }else{
            stopProgress();
            Toast.makeText(GoodForPayActivity.this,R.string.Wangluo,Toast.LENGTH_SHORT).show();
        }
    }

    //支付宝支付
    private void zhifubao() {
        String orderInfo = PayUtil.getNewOrderInfo(getString(R.string.app_name), "订单："+orderNo,car_cp_totalFee.getText().toString());//car_cp_totalFee.getText().toString()
        String sign = PayUtil.sign(orderInfo);
        try {
            // 仅需对sign 做URL编码
            sign = URLEncoder.encode(sign, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        // 完整的符合支付宝参数规范的订单信息
        final String payInfo = orderInfo + "&sign=\"" + sign + "\"&"
                + PayUtil.getSignType();


        Runnable payRunnable = new Runnable() {
            @Override
            public void run() {
                // 构造PayTask 对象0
                PayTask alipay = new PayTask(GoodForPayActivity.this);
                // 调用支付接口，获取支付结果
                String result = alipay.pay(payInfo);
                Message msg = new Message();
                msg.what = PayUtil.SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };

        // 必须异步调用
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

    //微信支付
    private void weixin() {
        GetPrepayIdTask getPrepayId = new GetPrepayIdTask();
        getPrepayId.execute();
    }

    /**
     * 初始化收获地址
     *
     * @description: 当用户存在收货地址时，读取用户的收货地址并显示，否则显示新建收货地址
     */
    private void initAddress() {
        noAddressL = (LinearLayout) findViewById(R.id.NoAddress);
        defaultAddressL = (LinearLayout) findViewById(R.id.defaultAddress);

        if(getIntent().getSerializableExtra("address")!=null){
            addressBean = (AddressBean)intent.getSerializableExtra("address");
            initAddress(addressBean);
            noAddressL.setVisibility(View.GONE);
            defaultAddressL.setVisibility(View.VISIBLE);
            defaultAddressL.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(GoodForPayActivity.this, AddressMangeActivity.class);
                    intent.putExtra("tag", "1");
                    intent.putExtra("biaoji", biaoji);
                    if(BaseApplication.getInstance().isWeixin) {
                        intent.putExtra("list", (Serializable) BaseApplication.getInstance().shopCarBeans);
                        order_jf_sub_je = discountMoney.getText().toString().split("￥")[1];
                    }else{
                        intent.putExtra("list", (Serializable) goodInfoList);
                    }
                    if(order_jf_sub_je!=null&&!"".equals(order_jf_sub_je)){
                        intent.putExtra("order_jf_sub_je",order_jf_sub_je);
                    }
                    startActivity(intent);
                    BaseApplication.getInstance().removeActivity(GoodForPayActivity.this);
                    finish();
                }
            });
        }else {
            //获取收货地址
            httpAddress();
        }
    }

    //获取收货地址
    private void httpAddress() {
        showProgress();
        if(Utils.isNetworkAvailable(GoodForPayActivity.this)){
            mRequestManager.requestGet(Request.Method.GET, Constants.ServiceInterFace.selectDefaultAddressURL + phone, Constants.RequestTag.selectDefaultAddressTag, map, AddressBeans.class);
        }else{
            Toast.makeText(GoodForPayActivity.this,R.string.Wangluo,Toast.LENGTH_SHORT).show();
        }

    }

    private void initAddress(AddressBean infoModle) {
        if (infoModle != null) {
            CommonStatus.isAddress = true;
            noAddressL.setVisibility(View.GONE);
            TextView userNameView = (TextView) findViewById(R.id.userName);
            TextView userPhone = (TextView) findViewById(R.id.userPhone);
            TextView userAddress = (TextView) findViewById(R.id.address);
            userNameView.setText(infoModle.getUser_name());
            userPhone.setText(infoModle.getUser_mobile());
            userAddress.setText(infoModle.getUser_address_sxq() + " " + infoModle.getUser_address_info());
            defaultAddressL.setVisibility(View.VISIBLE);
        } else {
            noAddressL.setVisibility(View.VISIBLE);
            defaultAddressL.setVisibility(View.GONE);
        }
    }

//    public void check() {
//        Runnable checkRunnable = new Runnable() {
//
//            @Override
//            public void run() {
//                // 构造PayTask 对象
//                PayTask payTask = new PayTask(GoodForPayActivity.this);
//                // 调用查询接口，获取查询结果
//                boolean isExist = payTask.checkAccountIfExist();
//                Message msg = new Message();
//                msg.what = PayUtil.SDK_CHECK_FLAG;
//                msg.obj = isExist;
//                mHandler.sendMessage(msg);
//            }
//        };
//
//        Thread checkThread = new Thread(checkRunnable);
//        checkThread.start();
//
//    }

    @Override
    public <T> void successResponse(T parsedGSON, int tag) {
        stopProgress();
        if (tag == Constants.RequestTag.selectDefaultAddressTag) {
            /** 判断返回值不为空 **/
            if (parsedGSON != null) {
                addressBeans = (AddressBeans) parsedGSON;
                if (addressBeans.getResult().equals("success")) {
                    //是否存在地址
                    if (addressBeans.getData() != null) {
                        addressBean = addressBeans.getData();
                        initAddress(addressBean);
                        noAddressL.setVisibility(View.GONE);
                        defaultAddressL.setVisibility(View.VISIBLE);
                        defaultAddressL.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                Intent intent = new Intent(GoodForPayActivity.this,AddressMangeActivity.class);
                                intent.putExtra("tag", "1");
                                intent.putExtra("biaoji", biaoji);
                                if(BaseApplication.getInstance().isWeixin) {
                                    intent.putExtra("list", (Serializable) BaseApplication.getInstance().shopCarBeans);
                                    order_jf_sub_je = discountMoney.getText().toString().split("￥")[1];
                                }else{
                                    intent.putExtra("list", (Serializable) goodInfoList);
                                }
                                if(order_jf_sub_je!=null&&!"".equals(order_jf_sub_je)){
                                    intent.putExtra("order_jf_sub_je",order_jf_sub_je);
                                }
                                startActivity(intent);
                                BaseApplication.getInstance().removeActivity(GoodForPayActivity.this);
                                finish();
                            }
                        });
                    } else {
                        defaultAddressL.setVisibility(View.GONE);
                        noAddressL.setVisibility(View.VISIBLE);
                        Button addBtn = (Button) findViewById(R.id.addAdressBtn);
                        //收获取址
                        addBtn.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                Intent intent = new Intent(GoodForPayActivity.this, AddressAddActivity.class);
                                intent.putExtra("tag", "1");
                                intent.putExtra("biaoji", biaoji);
                                if(BaseApplication.getInstance().isWeixin) {
                                    intent.putExtra("list", (Serializable) BaseApplication.getInstance().shopCarBeans);
                                    order_jf_sub_je = discountMoney.getText().toString().split("￥")[1];
                                }else{
                                    intent.putExtra("list", (Serializable) goodInfoList);
                                }
                                if(order_jf_sub_je!=null&&!"".equals(order_jf_sub_je)){
                                    intent.putExtra("order_jf_sub_je",order_jf_sub_je);
                                }
                                startActivity(intent);
                                BaseApplication.getInstance().removeActivity(GoodForPayActivity.this);
                                finish();
                            }
                        });
                    }
                }
            }
        }
        if (tag == Constants.RequestTag.selectJiFenTag) {
            /** 判断返回值不为空 **/
            if (parsedGSON != null) {
                jiFenBeans = (JiFenBeans) parsedGSON;
                if(jiFenBeans!=null){
                    if(jiFenBeans.getResult().equals("success")) {
                        jifen.setText("可用积分:" + jiFenBeans.getData().getAvailable_point());
                        //初始化数据
                        initListViewData();
                        //初始化视图
                        initListView();
                        //初始化收获地址
                        initAddress();
                        //初始化按钮
                        initBottomBtn();
                        //监听
                        setListener();
                    }else{
                        Toast.makeText(GoodForPayActivity.this,jiFenBeans.getMsg(),Toast.LENGTH_SHORT).show();
                    }
                }
            }
        }
        if (tag == Constants.RequestTag.addOrderTag) {
            /** 判断返回值不为空 **/
            if (parsedGSON != null) {
                baseBean = (BaseBean) parsedGSON;
                if(baseBean.getResult().equals("success")){
                    if(car_cp_totalFee.getText().toString().equals("0")||car_cp_totalFee.getText().toString().equals("0.0")||car_cp_totalFee.getText().toString().equals("0.00")){
                        pre_id="积分支付";
                        httpPaySuccess();
                        return;
                    }

                    if ("1".equals(payWay)) {
                        zhifubao();
                    } else if ("2".equals(payWay)) {
                        weixin();
                    } else {
                        Toast.makeText(GoodForPayActivity.this, "请选择支付方式", Toast.LENGTH_SHORT).show();
                    }
                }else{
                    Toast.makeText(GoodForPayActivity.this, baseBean.getMsg(), Toast.LENGTH_SHORT).show();
                }
            }
        }
        if (tag == Constants.RequestTag.updatePayTypeTag) {
            /** 判断返回值不为空 **/
            if (parsedGSON != null) {
                baseBean = (BaseBean) parsedGSON;
                if(baseBean.getResult().equals("success")){
                    if(car_cp_totalFee.getText().toString().equals("0")||car_cp_totalFee.getText().toString().equals("0.0")||car_cp_totalFee.getText().toString().equals("0.00")){
                        pre_id="积分支付";
                        httpPaySuccess();
                        return;
                    }

                    if ("1".equals(payWay)) {
                        zhifubao();
                    } else if ("2".equals(payWay)) {
                        weixin();
                    } else {
                        Toast.makeText(GoodForPayActivity.this, "请选择支付方式", Toast.LENGTH_SHORT).show();
                    }
                }else{
                    Toast.makeText(GoodForPayActivity.this, baseBean.getMsg(), Toast.LENGTH_SHORT).show();
                }
            }
        }
        if (tag == Constants.RequestTag.paySuccessTag) {
            /** 判断返回值不为空 **/
            if (parsedGSON != null) {
                baseBean = (BaseBean) parsedGSON;
                if(baseBean.getResult().equals("success")){
                    orderNo="";
                    Toast.makeText(GoodForPayActivity.this, baseBean.getMsg(), Toast.LENGTH_LONG).show();
                    Intent intent  = new Intent(GoodForPayActivity.this,OrderActivity.class);
                    intent.putExtra("biaoji",biaoji);
                    Bundle bl = new Bundle();
                    bl.putSerializable(StaticData.ORDER_TYPE,StaticData.ALL_ORDER);
                    intent.putExtra("bundle", bl);
                    startActivity(intent);
                    BaseApplication.getInstance().removeActivity(GoodForPayActivity.this);
                    BaseApplication.getInstance().removeActivitytwo();
                    finish();
                }else{
                    Toast.makeText(GoodForPayActivity.this, baseBean.getMsg(), Toast.LENGTH_LONG).show();
                    Log.e("msg", baseBean.getMsg());
                }
            }
        }
        if (tag == Constants.RequestTag.selectShopCarTag) {
            if (parsedGSON != null) {
                shopCarListBean = (ShopCarListBean) parsedGSON;
                // 判断是否是有数据
                if (shopCarListBean.getResult().equals("success")) {// 成功
                    if (shopCarListBean.getData().size() > 0) {//获取到数据
                        for(int i=0;i<shopCarListBean.getData().size();i++){
                            if(shopCarListBean.getData().get(i).getGoods_status().equals("1")){
                                goodInfoList.add(shopCarListBean.getData().get(i));
                            }
                        }
                        if(goodInfoList.size()<=0){
                            goodInfoList=BaseApplication.getInstance().shopCarBeans;
                            ShopCarBean item;
                            totalPrice= new BigDecimal(0);
                            for (int i = 0; i < goodInfoList.size(); i++) {
                                item = goodInfoList.get(i);
                                totalPrice=totalPrice.add(new BigDecimal(String.valueOf(item.getGoods_count())).multiply(new BigDecimal(String.valueOf(item.getGoods_new_price())))) ;
                            }
                            if (order_jf_sub_je != null && !"".equals(order_jf_sub_je)) {
                                discountMoney.setText("￥" + order_jf_sub_je);
                                edit_jifen_payMoney.setText(new BigDecimal(discountMoney.getText().toString().split("￥")[1]).multiply(new BigDecimal(100)).setScale(0, BigDecimal.ROUND_HALF_UP).toString());
                            }
                            shiyong_money.setText("已使用");
                            edit_jifen_payMoney.setFocusable(false);
//                            discountMoney.setText("￥" + new BigDecimal(edit_jifen_payMoney.getText().toString()).divide(new BigDecimal(100)).setScale(2, BigDecimal.ROUND_HALF_UP).toString());
                            hyyh.setText(new BigDecimal(edit_jifen_payMoney.getText().toString()).divide(new BigDecimal(100)).setScale(2, BigDecimal.ROUND_HALF_UP).toString());
                            car_cp_totalFee.setText(totalPrice.subtract(new BigDecimal(hyyh.getText().toString())).setScale(2, BigDecimal.ROUND_HALF_UP).toString());
                            orderZongJi.setText(totalPrice.setScale(2, BigDecimal.ROUND_HALF_UP).toString());//订单总计
                            shifu.setText(totalPrice.subtract(new BigDecimal(hyyh.getText().toString())).setScale(2, BigDecimal.ROUND_HALF_UP).toString());//实付
                            adapter.setList(goodInfoList);
                            adapter.notifyDataSetChanged();
                        }else {
                            orderNo="";
                            BaseApplication.getInstance().shopCarBeans = goodInfoList;
                            ShopCarBean item;
                            totalPrice = new BigDecimal(0);
                            for (int i = 0; i < goodInfoList.size(); i++) {
                                item = goodInfoList.get(i);
                                totalPrice = totalPrice.add(new BigDecimal(String.valueOf(item.getGoods_count())).multiply(new BigDecimal(String.valueOf(item.getGoods_new_price()))));
                            }
                            if ((totalPrice.multiply(new BigDecimal(100)).intValue()) > Integer.parseInt(jiFenBeans.getData().getAvailable_point())) {
                                edit_jifen_payMoney.setText(jiFenBeans.getData().getAvailable_point()+"");
                            } else {
                                edit_jifen_payMoney.setText(totalPrice.multiply(new BigDecimal(100)).setScale(0, BigDecimal.ROUND_HALF_UP).toString());
                            }
                            discountMoney.setText("￥" + new BigDecimal(edit_jifen_payMoney.getText().toString()).divide(new BigDecimal(100)).setScale(2, BigDecimal.ROUND_HALF_UP).toString());
                            hyyh.setText(new BigDecimal(edit_jifen_payMoney.getText().toString()).divide(new BigDecimal(100)).setScale(2, BigDecimal.ROUND_HALF_UP).toString());
                            car_cp_totalFee.setText(totalPrice.subtract(new BigDecimal(hyyh.getText().toString())).setScale(2, BigDecimal.ROUND_HALF_UP).toString());
                            orderZongJi.setText(totalPrice.setScale(2, BigDecimal.ROUND_HALF_UP).toString());//订单总计
                            shifu.setText(totalPrice.subtract(new BigDecimal(hyyh.getText().toString())).setScale(2, BigDecimal.ROUND_HALF_UP).toString());//实付
                            adapter.setList(goodInfoList);
                            adapter.notifyDataSetChanged();
                        }
                    }else{
                        if(BaseApplication.getInstance().shopCarBeans.size()>0){
                            goodInfoList=BaseApplication.getInstance().shopCarBeans;
                            ShopCarBean item;
                            totalPrice= new BigDecimal(0);
                            for (int i = 0; i < goodInfoList.size(); i++) {
                                item = goodInfoList.get(i);
                                totalPrice=totalPrice.add(new BigDecimal(String.valueOf(item.getGoods_count())).multiply(new BigDecimal(String.valueOf(item.getGoods_new_price())))) ;
                            }
                            if (order_jf_sub_je != null && !"".equals(order_jf_sub_je)) {
                                discountMoney.setText("￥" + order_jf_sub_je);
                                edit_jifen_payMoney.setText(new BigDecimal(discountMoney.getText().toString().split("￥")[1]).multiply(new BigDecimal(100)).setScale(0, BigDecimal.ROUND_HALF_UP).toString());
                            }
                            shiyong_money.setText("已使用");
                            edit_jifen_payMoney.setFocusable(false);
                            hyyh.setText(new BigDecimal(edit_jifen_payMoney.getText().toString()).divide(new BigDecimal(100)).setScale(2, BigDecimal.ROUND_HALF_UP).toString());
                            car_cp_totalFee.setText(totalPrice.subtract(new BigDecimal(hyyh.getText().toString())).setScale(2, BigDecimal.ROUND_HALF_UP).toString());
                            orderZongJi.setText(totalPrice.setScale(2, BigDecimal.ROUND_HALF_UP).toString());//订单总计
                            shifu.setText(totalPrice.subtract(new BigDecimal(hyyh.getText().toString())).setScale(2, BigDecimal.ROUND_HALF_UP).toString());//实付
                            adapter.setList(goodInfoList);
                            adapter.notifyDataSetChanged();
                        }
                    }
                }
            }
        }
        if (tag == Constants.RequestTag.selectKunCunTag) {
            /** 判断返回值不为空 **/
            if (parsedGSON != null) {
                kuCunListBean = (KuCunListBean) parsedGSON;
                if(kuCunListBean.getResult().equals("success")){
                    if(kuCunListBean.getData().size()>0){
                        kuCunBeans = kuCunListBean.getData();
                        for(int i=0;i<kuCunBeans.size();i++){
                            kunCunMap.put(kuCunBeans.get(i).getGoods_id(),kuCunBeans.get(i).getStore_counts());
                        }
                        for(int i=0;i<goodInfoList.size();i++){
                            if(Integer.parseInt(goodInfoList.get(i).getGoods_count())>Integer.parseInt(kunCunMap.get(goodInfoList.get(i).getGoods_id()))){
                                Toast.makeText(GoodForPayActivity.this, goodInfoList.get(i).getGoods_title()+"库存不足!", Toast.LENGTH_SHORT).show();
                                return;
                            }
                        }
                        if ("".equals(orderNo) || orderNo == null) {
                            //生成订单编码
                            Date data = new Date();
                            SimpleDateFormat simple = new SimpleDateFormat("yyyyMMddhhmmssSSSss");
                            String time = simple.format(data);
                            orderNo = 20 + time;
                            httpAddOrder();
                        } else {
                            //修改支付方式
                            httpUpdatePayType();
                        }

                    }
                }
            }
        }

    }

    @Override
    public void errorResonse(String retmeg, int tag) {
        stopProgress();
        Toast.makeText(GoodForPayActivity.this, R.string.noWangluo, Toast.LENGTH_LONG).show();
    }
    //微信支付

    /**
     生成签名
     */
    private String genPackageSign(List<NameValuePair> params) {
        StringBuilder sb = new StringBuilder();

        for (int i = 0; i < params.size(); i++) {
            sb.append(params.get(i).getName());
            sb.append('=');
            sb.append(params.get(i).getValue());
            sb.append('&');
        }
        sb.append("key=");
        sb.append(com.kbt.simcpux.Constants.API_KEY);


        String packageSign = MD5.MD5Encode(sb.toString(), "utf-8");
        Log.e("orion",packageSign);
        return packageSign;
    }
    private String genAppSign(List<NameValuePair> params) {
        StringBuilder sb = new StringBuilder();

        for (int i = 0; i < params.size(); i++) {
            sb.append(params.get(i).getName());
            sb.append('=');
            sb.append(params.get(i).getValue());
            sb.append('&');
        }
        sb.append("key=");
        sb.append(com.kbt.simcpux.Constants.API_KEY);

        this.sb.append("sign str\n" + sb.toString() + "\n\n");
        String appSign = MD5.MD5Encode(sb.toString(),"utf-8");
        Log.e("orion", appSign);
        return appSign;
    }
    private String toXml(List<NameValuePair> params) {
        StringBuilder sb = new StringBuilder();
        sb.append("<xml>");
        for (int i = 0; i < params.size(); i++) {
            sb.append("<"+params.get(i).getName()+">");


            sb.append(params.get(i).getValue());
            sb.append("</"+params.get(i).getName()+">");
        }
        sb.append("</xml>");

        Log.e("orion",sb.toString());
        return sb.toString();
    }

    private class GetPrepayIdTask extends AsyncTask<Void, Void, Map<String,String>> {

        private ProgressDialog dialog;


        @Override
        protected void onPreExecute() {
            dialog = ProgressDialog.show(GoodForPayActivity.this, getString(R.string.app_tip), getString(R.string.getting_prepayid));
        }

        @Override
        protected void onPostExecute(Map<String,String> result) {
            if (dialog != null) {
                dialog.dismiss();
            }
            resultunifiedorder=result;
            //生成签名参数
            genPayReq();

        }

        @Override
        protected void onCancelled() {
            super.onCancelled();
        }

        @Override
        protected Map<String,String>  doInBackground(Void... params) {

            String url = String.format("https://api.mch.weixin.qq.com/pay/unifiedorder");
            String entity = genProductArgs();

            Log.e("orion",entity);

            byte[] buf = Util.httpPost(url, entity);

            String content = new String(buf);
            Log.e("orion", content);
            Map<String,String> xml=decodeXml(content);

            return xml;
        }
    }



    public Map<String,String> decodeXml(String content) {

        try {
            Map<String, String> xml = new HashMap<String, String>();
            XmlPullParser parser = Xml.newPullParser();
            parser.setInput(new StringReader(content));
            int event = parser.getEventType();
            while (event != XmlPullParser.END_DOCUMENT) {

                String nodeName=parser.getName();
                switch (event) {
                    case XmlPullParser.START_DOCUMENT:

                        break;
                    case XmlPullParser.START_TAG:

                        if("xml".equals(nodeName)==false){
                            //实例化student对象
                            xml.put(nodeName,parser.nextText());
                        }
                        break;
                    case XmlPullParser.END_TAG:
                        break;
                }
                event = parser.next();
            }

            return xml;
        } catch (Exception e) {
            Log.e("orion",e.toString());
        }
        return null;

    }


    private String genNonceStr() {
        Random random = new Random();
        return MD5.MD5Encode(String.valueOf(random.nextInt(10000)), "utf-8");
    }

    private long genTimeStamp() {
        return System.currentTimeMillis() / 1000;
    }



    private String genOutTradNo() {
        Random random = new Random();
        return MD5.MD5Encode(String.valueOf(random.nextInt(10000)), "utf-8");
    }


    //
    private String genProductArgs() {
        StringBuffer xml = new StringBuffer();

        try {
            String	nonceStr = genNonceStr();
            xml.append("</xml>");
            List<NameValuePair> packageParams = new LinkedList<NameValuePair>();
            packageParams.add(new BasicNameValuePair("appid", com.kbt.simcpux.Constants.APP_ID));
            packageParams.add(new BasicNameValuePair("body", getString(R.string.app_name)));
            packageParams.add(new BasicNameValuePair("mch_id", com.kbt.simcpux.Constants.MCH_ID));
            packageParams.add(new BasicNameValuePair("nonce_str", nonceStr));
            packageParams.add(new BasicNameValuePair("notify_url", "http://m.kua-jie.com/tenpay_api_b2c/payNotifyUrl"));
            packageParams.add(new BasicNameValuePair("out_trade_no",pre_id));
            packageParams.add(new BasicNameValuePair("spbill_create_ip", "127.0.0.1"));
            packageParams.add(new BasicNameValuePair("total_fee", ""+new BigDecimal(car_cp_totalFee.getText().toString()).multiply(new BigDecimal(100)).intValue()));//+new BigDecimal(car_cp_totalFee.getText().toString()).multiply(new BigDecimal(100)).intValue()
            packageParams.add(new BasicNameValuePair("trade_type", "APP"));

            String sign = genPackageSign(packageParams);
            packageParams.add(new BasicNameValuePair("sign", sign));
            String xmlstring =toXml(packageParams);
            return new String(xmlstring.toString().getBytes(), "ISO8859-1");

        } catch (Exception e) {
            Log.e("tag", "genProductArgs fail, ex = " + e.getMessage());
            return null;
        }


    }
    private void genPayReq() {

        req.appId = com.kbt.simcpux.Constants.APP_ID;
        req.partnerId = com.kbt.simcpux.Constants.MCH_ID;
        req.prepayId = resultunifiedorder.get("prepay_id");
        req.packageValue = "Sign=WXPay";
        req.nonceStr = genNonceStr();
        req.timeStamp = String.valueOf(genTimeStamp());


        List<NameValuePair> signParams = new LinkedList<NameValuePair>();
        signParams.add(new BasicNameValuePair("appid", req.appId));
        signParams.add(new BasicNameValuePair("noncestr", req.nonceStr));
        signParams.add(new BasicNameValuePair("package", req.packageValue));
        signParams.add(new BasicNameValuePair("partnerid", req.partnerId));
        signParams.add(new BasicNameValuePair("prepayid", req.prepayId));
        signParams.add(new BasicNameValuePair("timestamp", req.timeStamp));

        req.sign = genAppSign(signParams);
//
//		sb.append("sign\n"+req.sign+"\n\n");
//
//		show.setText(sb.toString());
        sendPayReq();

        Log.e("orion", signParams.toString());

    }
    private void sendPayReq() {
        msgApi.registerApp(com.kbt.simcpux.Constants.APP_ID);
        msgApi.sendReq(req);
    }

    /**
     * progressDialog的展示
     */
    public void showProgress() {
        if (mProgress == null) {
            mProgress = new LoadingDialog(GoodForPayActivity.this,"");
            mProgress.setCancelable(true);
            mProgress.show();
        } else {
            if (mProgress.isShowing()) {
                stopProgress();
            } else {
                mProgress.show();
            }
        }
    }


    /**
     * progressDialog的消失
     */
    public void stopProgress() {
        if (mProgress != null) {
            mProgress.dismiss();
            mProgress = null;
        }
    }
    private TextWatcher textWatcher = new TextWatcher() {

        @Override
        public void afterTextChanged(Editable s) {
            // TODO Auto-generated method stub
            Log.d("TAG", "afterTextChanged--------------->");
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                                      int after) {
            // TODO Auto-generated method stub
            Log.d("TAG", "beforeTextChanged--------------->");
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before,
                                  int count) {
            Log.d("TAG","onTextChanged--------------->");
            double jifen_window = 0;
            if("".equals(edit_jifen_payMoney.getText().toString())||edit_jifen_payMoney.getText().toString()==null){
                edit_jifen_payMoney.setText("0");
            }
            String jifen_money = edit_jifen_payMoney.getText().toString();
            if(jifen_money.length()>1) {
                if (String.valueOf(jifen_money.charAt(0)).equals("0")) {
                    jifen_window = new BigDecimal(jifen_money.substring(1)).setScale(0,BigDecimal.ROUND_HALF_UP).doubleValue();
                    edit_jifen_payMoney.setText(new BigDecimal(jifen_window).setScale(0,BigDecimal.ROUND_HALF_UP).toString());
                    edit_jifen_payMoney.setSelection(edit_jifen_payMoney.getText().toString().length());
                } else {
                    jifen_window =new BigDecimal(jifen_money).setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue();
                }
            }else{
                if(!String.valueOf(jifen_money.charAt(0)).equals("0")){
                    jifen_window = new BigDecimal(jifen_money).setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue();
                }
            }
            if (jifen_window <= Integer.parseInt(jiFenBeans.getData().getAvailable_point())) {
                double duihuan_money = jifen_window / 100.0;
                double jifenmoney = totalPrice.doubleValue();
                if(duihuan_money>jifenmoney){
                    String money_edit = edit_jifen_payMoney.getText().toString();
                    edit_jifen_payMoney.setText(money_edit.substring(0, money_edit.length() - 1) + "");
                    edit_jifen_payMoney.setSelection(edit_jifen_payMoney.getText().toString().length());//光标位置
                    double youhuimoney = Double.parseDouble(edit_jifen_payMoney.getText().toString()) / 100.0;
                    discountMoney.setText("￥" + youhuimoney);
                    if (edit_jifen_payMoney.getText().toString().equals("0")) {
                        double zongjiMoney = Double.parseDouble(orderZongJi.getText().toString());
                        shifu.setText(new BigDecimal(zongjiMoney+"").setScale(2,BigDecimal.ROUND_HALF_UP).toString());
                        car_cp_totalFee.setText(new BigDecimal(zongjiMoney+"").setScale(2,BigDecimal.ROUND_HALF_UP).toString());
                    }
                    double shifuMoney = Double.parseDouble(orderZongJi.getText().toString()) - Double.parseDouble(discountMoney.getText().toString().split("￥")[1]);
                    shifu.setText(new BigDecimal(shifuMoney+"").setScale(2,BigDecimal.ROUND_HALF_UP).toString());
                    hyyh.setText(new BigDecimal(youhuimoney+"").setScale(2,BigDecimal.ROUND_HALF_UP) + "");
                    car_cp_totalFee.setText(new BigDecimal(shifuMoney+"").setScale(2,BigDecimal.ROUND_HALF_UP).toString());
                    Toast.makeText(GoodForPayActivity.this, "您最多抵扣" + new DecimalFormat("#.##").format(jifenmoney * 100) + "积分", Toast.LENGTH_SHORT).show();
                    return;
                }

                discountMoney.setText("￥"+duihuan_money);
                if (edit_jifen_payMoney.getText().toString().equals("0")) {
                    double zongjiMoney = Double.parseDouble(orderZongJi.getText().toString());
                    shifu.setText(new BigDecimal(zongjiMoney+"").setScale(2,BigDecimal.ROUND_HALF_UP).toString());
                    car_cp_totalFee.setText(new BigDecimal(zongjiMoney+"").setScale(2,BigDecimal.ROUND_HALF_UP).toString());
                }
                double shifuMoney = Double.parseDouble(orderZongJi.getText().toString()) - Double.parseDouble(discountMoney.getText().toString().split("￥")[1]);
                shifu.setText(new BigDecimal(shifuMoney+"").setScale(2,BigDecimal.ROUND_HALF_UP).toString());
                hyyh.setText(new BigDecimal(duihuan_money+"").setScale(2,BigDecimal.ROUND_HALF_UP) + "");
                car_cp_totalFee.setText(new BigDecimal(shifuMoney+"").setScale(2,BigDecimal.ROUND_HALF_UP).toString());
            } else {
                String money_edit = edit_jifen_payMoney.getText().toString();
                edit_jifen_payMoney.setText(money_edit.substring(0, money_edit.length() - 1) + "");
                edit_jifen_payMoney.setSelection(edit_jifen_payMoney.getText().toString().length());//光标位置
                double youhuimoney = Double.parseDouble(edit_jifen_payMoney.getText().toString()) / 100.0;
                discountMoney.setText("￥" + youhuimoney);
                if (edit_jifen_payMoney.getText().toString().equals("0")) {
                    double zongjiMoney = Double.parseDouble(orderZongJi.getText().toString());
                    shifu.setText(new BigDecimal(zongjiMoney+"").setScale(2,BigDecimal.ROUND_HALF_UP).toString());
                    car_cp_totalFee.setText(new BigDecimal(zongjiMoney+"").setScale(2,BigDecimal.ROUND_HALF_UP).toString());
                }
                double shifuMoney = Double.parseDouble(orderZongJi.getText().toString()) - Double.parseDouble(discountMoney.getText().toString().split("￥")[1]);
                hyyh.setText(new BigDecimal(youhuimoney+"").setScale(2,BigDecimal.ROUND_HALF_UP) + "");
                shifu.setText(new BigDecimal(shifuMoney+"").setScale(2,BigDecimal.ROUND_HALF_UP).toString());
                car_cp_totalFee.setText(new BigDecimal(shifuMoney+"").setScale(2,BigDecimal.ROUND_HALF_UP).toString());
                Toast.makeText(GoodForPayActivity.this, "积分不足！", Toast.LENGTH_SHORT).show();
            }

        }
    };
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event)
    {
        if (keyCode == KeyEvent.KEYCODE_BACK )
        {
            BaseApplication.getInstance().removeActivity(GoodForPayActivity.this);
            if ("shopcar".equals(biaoji)) {
                Intent intent = new Intent(GoodForPayActivity.this, StoreActivity.class);
                startActivity(intent);
            } else if ("buyNow".equals(biaoji)) {
                Intent intent = new Intent(GoodForPayActivity.this, GoodInfoActivity.class);
                intent.putExtra("shopId", goodInfoList.get(0).getGoods_id());
                startActivity(intent);
            }
            finish();
        }

        return false;

    }




}
